package com.haixiaoke.saas.system.controller.system;


import cn.hutool.core.util.ObjectUtil;
import com.haixiaoke.saas.common.annotation.TenantScope;
import com.haixiaoke.saas.common.constant.Constants;
import com.haixiaoke.saas.common.constant.PlatformConstants;
import com.haixiaoke.saas.common.constant.TenantConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.domain.entity.SysMenu;
import com.haixiaoke.saas.common.core.domain.entity.SysUser;
import com.haixiaoke.saas.common.tenant.TenantContext;
import com.haixiaoke.saas.common.weChat.domain.WeChatLoginParam;
import com.haixiaoke.saas.department.domain.Tenant;
import com.haixiaoke.saas.department.service.ITenantService;
import com.haixiaoke.saas.user.domain.BizTenantUser;
import com.haixiaoke.saas.user.domain.BizUserBusiness;
import com.haixiaoke.saas.system.domain.LoginBody;
import com.haixiaoke.saas.system.domain.LoginUser;
import com.haixiaoke.saas.system.framework.security.util.SecurityUtils;
import com.haixiaoke.saas.system.framework.web.service.SysLoginService;
import com.haixiaoke.saas.system.framework.web.service.SysPermissionService;
import com.haixiaoke.saas.system.framework.web.service.TokenService;
import com.haixiaoke.saas.system.service.ISysMenuService;
import com.haixiaoke.saas.user.domain.UserConsumer;
import com.haixiaoke.saas.user.service.IBizTenantUserService;
import com.haixiaoke.saas.user.service.IBizUserBusinessService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 登录验证
 *
 * @author haixiaoke
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IBizTenantUserService bizDepartmentUserService;

    @Autowired
    private ITenantService tenantService;

    @Autowired
    private IBizUserBusinessService userBusinessService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/enterprise/login")
    public AjaxResult enterpriseLogin(@RequestBody LoginBody loginBody) {
        if (loginBody.getPlatform() == null || (!PlatformConstants.PC_BUSINESS.equals(loginBody.getPlatform()) && !PlatformConstants.MP_WECHAT_BUSINESS.equals(loginBody.getPlatform()))) {
            return AjaxResult.error("登录错误！检查所选平台");
        }
        if (StringUtils.isBlank(loginBody.getTenantId()) || !bizDepartmentUserService.checkUserByDepId(loginBody.getTenantId(), loginBody.getPhonenumber())) {
            return AjaxResult.error("该用户不存在该机构");
        }
        Tenant tenant = tenantService.selectDepartmentByDepId(loginBody.getTenantId());
        if (TenantConstants.TENANT_STATUS_NO.equals(tenant.getTenantStatus())) {
            return AjaxResult.error("该机构已被禁用");
        }
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        LoginUser loginUser = loginService.enterpriseLogin(loginBody.getPhonenumber(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), loginBody.getPlatform(), loginBody.getTenantId());
        String token = tokenService.createToken(loginUser);
        ajax.put(Constants.TOKEN, token);
        ajax.put(Constants.TENANTID, loginUser.getTenantId());
        return ajax;
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/manage/login")
    public AjaxResult manageLogin(@RequestBody LoginBody loginBody) {
        if (loginBody.getPlatform() == null || !PlatformConstants.PC_BUSINESS.equals(loginBody.getPlatform())) {
            return AjaxResult.error("登录错误！检查所选平台");
        }
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        LoginUser loginUser = loginService.manageLogin(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid(), loginBody.getPlatform());
        String token = tokenService.createToken(loginUser);
        ajax.put(Constants.TOKEN, token);
        ajax.put(Constants.TENANTID, loginUser.getTenantId());
        return ajax;
    }


    /**
     * 登录方法-微信一键登录
     */
    @PostMapping("/weChat/login")
    public AjaxResult weChatLogin(@RequestBody LoginBody loginBody) {
        Tenant tenant = tenantService.selectDepartmentByDepId(loginBody.getTenantId());
        if (TenantConstants.TENANT_STATUS_NO.equals(tenant.getTenantStatus())) {
            return AjaxResult.error("该机构已被禁用");
        }
        LoginUser loginUser = userBusinessService.weChatSelectUserByPhone(loginBody);
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        loginUser.setTenantId(loginBody.getTenantId());
        loginUser.setPlatform(PlatformConstants.MP_WECHAT_BUSINESS);
        String token = tokenService.createToken(loginUser);
        ajax.put(Constants.TOKEN, token);
        ajax.put(Constants.TENANTID, loginUser.getTenantId());
        return ajax;
    }


    /**
     * 登录方法-手机验证码登录
     */
    @PostMapping("/captcha/login")
    public AjaxResult captchaLogin(@RequestBody LoginBody loginBody) {
        Tenant tenant = tenantService.selectDepartmentByDepId(loginBody.getTenantId());
        if (TenantConstants.TENANT_STATUS_NO.equals(tenant.getTenantStatus())) {
            return AjaxResult.error("该机构已被禁用");
        }
        LoginUser loginUser = loginService.captchaLogin(loginBody.getPhonenumber(), loginBody.getCode(), loginBody.getTenantId());
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        loginUser.setTenantId(loginBody.getTenantId());
        loginUser.setPlatform(PlatformConstants.MP_WECHAT_BUSINESS);
        String token = tokenService.createToken(loginUser);
        ajax.put(Constants.TOKEN, token);
        ajax.put(Constants.TENANTID, loginUser.getTenantId());
        return ajax;
    }


    /**
     * 获取企业端用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/enterprise/getInfo")
    public AjaxResult enterpriseGetInfo() {
        BizUserBusiness user = SecurityUtils.getLoginUser().getBizUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user.getUserId(), SecurityUtils.getLoginUser().getTenantId());
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user, SecurityUtils.getLoginUser().getTenantId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取后管用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/manage/getInfo")
    public AjaxResult manageGetInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/enterprise/getRouters")
    @TenantScope
    public AjaxResult enterpriseGetRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByBizUserId(userId, TenantContext.getTenantId(),
                SecurityUtils.getLoginUser().getBizUser().getRoleId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/manage/getRouters")
    public AjaxResult manageGetRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 微信获取手机号码
     */
    @PostMapping("/weChat/getPhoneNumber")
    public AjaxResult getPhoneNumber(@RequestBody LoginBody loginBody) {
        return AjaxResult.success(loginService.getPhoneNumber(loginBody));
    }
}
